package cn.yong.dao;

import cn.yong.entity.Emp;
import cn.yong.entity.EmpCondition;
import org.hibernate.Query;

import java.util.Iterator;
import java.util.List;

public class EmpDao extends BaseDao {

    public List<Emp> findList(){

        List<Emp> list=null;

        String hql = "from Emp";
        Query query = super.currentSession().createQuery(hql);
        list = query.list();

        return list;
    }

    public Iterator<Emp> findIterae(){
        Iterator<Emp> iterator=null;
        String hql = "from Emp";
        Query query = super.currentSession().createQuery(hql);
        iterator = query.iterate();
        return iterator;
    }

    public List<Emp> findByConditions(Object[] conditions) {

        String hql = "from Emp where job = ? and sal > ?";

        Query query = currentSession().createQuery(hql);

        if (conditions != null && conditions.length > 0) {
            for (int i = 0; i < conditions.length; ++i) {
                query.setParameter(i, conditions[i]); // 为占位符赋值
            }
        }
        return query.list();
    }

    public List<Emp> findByConditions(Emp conditions) {
        String hql = "from Emp where job = :job and sal > :sal";
        Query query = currentSession().createQuery(hql);
        query.setProperties(conditions); // 根据参数名获取相应的属性值进行赋值
        return query.list();
    }

    public List<Emp> findByConditions(String hql, EmpCondition conditions) {
        return currentSession().createQuery(hql) // 创建Query对象
                .setProperties(conditions) // 为参数赋值
                .list(); // 执行查询，获取查询结果
    }

    public Long obtainTheRowCount(Double sal) {
        String hql = "select count(id) from Emp where sal >= :sal";
        return (Long) currentSession().createQuery(hql)
                .setDouble("sal", sal)
                .uniqueResult(); // 执行返回唯一结果，以Object类型封装
    }

    // select * form emp limit 0,5   //起始索引，页面大小

    public List<Emp> findByPage(int beginIndex, int pageSize) {
        String hql = "from Emp order by id";

        Query query = currentSession().createQuery(hql);

        query .setFirstResult(beginIndex); // 设置获取结果的起始下标
        query .setMaxResults(pageSize); // 设置最大返回结果数

        return  query.list();
    }

    public  void save(Emp emp){
        super.currentSession().save(emp);
    }

    public List<Emp> findByInvisibleJoin(String deptName){
        String hql = "from Emp e  where e.dept.deptName=?";
        return currentSession().createQuery(hql).setString(0,deptName).list();
    }

    public List<Object[]> findGroupBy(){
        String hql = "select e.job, count(e) from Emp e group by e.job";
        return currentSession().createQuery(hql).list();
    }
}
